package com.lydms.service.impl;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.lydms.service.ImageOcrService;
import com.lydms.thirdparty.BaiDuOcr;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class ImageOcrServiceImpl implements ImageOcrService {
    private static final Logger logger = LogManager.getLogger(ImageOcrServiceImpl.class);

    //  注入百度翻译。
    @Autowired
    private BaiDuOcr baiDuOcr;


    /**
     * 通用识别文字
     *
     * @param image
     * @return
     */
    @Override
    public String ocrCommon(byte[] image) {
        StringBuffer buffer = new StringBuffer();

//        1、调用百度OCR服务
        String result = baiDuOcr.sample(image);
        logger.info("调用百度OCR以后的返回值为:{}", result.toString());

//        2、返回值的处理
        if (result == null) {
            logger.info("调用服务失败");
            return null;
        }
//        内容解析
        ObjectMapper mapper = new ObjectMapper();
        try {
            Map words = mapper.readValue(result, Map.class);
            List wordsList = (ArrayList) words.get("words_result");
            for (int i = 0; i < wordsList.size(); i++) {
                Map m = (Map) wordsList.get(i);
                String word = m.get("words").toString();
                buffer.append(word);
            }
        } catch (IOException e) {
            logger.info("格式转换出现异常");
            return null;
        }
        String font = buffer.toString();
        logger.info("翻译后的文字为:{}", font);
        return font;
    }


}
